package com.xixi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xixi.entity.User;
import com.xixi.mapper.UserMapper;
import com.xixi.pojo.dto.LoginUserDTO;
import com.xixi.pojo.dto.UserDTO;
import com.xixi.pojo.query.UserQueryPage;
import com.xixi.pojo.vo.Result;
import com.xixi.pojo.vo.UserVO;
import com.xixi.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.hutool.core.util.RandomUtil.randomNumbers;
import static com.xixi.utils.ValidatorUtil.isValidPhone;
import static com.xixi.utils.ValidatorUtil.validatePhoneWithDetail;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        if (!isValidPhone(phone)) {
            String message = validatePhoneWithDetail(phone);
            return Result.error(message);
        }
        String code = randomNumbers(6);
        session.setAttribute("code", code);
        log.info("发送验证码：{}", code);
        return Result.success();
    }
    @Override
    public LoginUserDTO userLogin(LoginUserDTO loginUserDTO) {
        return userMapper.userLogin(loginUserDTO);
    }

    @Override
    public List<UserVO> list() {
        List<UserVO> list = userMapper.list();
        return list;
    }
    @Override
    public UserVO getUserById(Integer id) {
        UserVO userVO = userMapper.getUserById(id);
        return userVO;
    }

    @Override
    public IPage<UserVO> getUserPage(UserQueryPage userQueryPage) {
        IPage<UserVO> page = new Page<>(userQueryPage.getPageNum(), userQueryPage.getPageSize());
        return userMapper.getUserPage(page, userQueryPage);
    }

    @Override
    public Result insert(UserDTO userDTO) {
        User user= BeanUtil.toBean(userDTO, User.class);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        if (userMapper.insert(user) > 0) {
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    @Override
    public Result update(UserDTO userDTO) {
        User user= BeanUtil.toBean(userDTO, User.class);
        user.setUpdateTime(LocalDateTime.now());
        if (userMapper.updateById(user) > 0) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @Override
    public Result delete(List<Integer> ids) {
        if (userMapper.deleteBatchIds(ids) > 0) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
}
